註冊系統完成後接下來就是登入的部分(延續上篇使用Django內建的會員系統)。
from django.contrib import auth
def post_login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user and user.is_staff is False:
auth.login(request, user)
return redirect('/login/')
elif user and user.is_staff is True:
auth.login(request, user)
return redirect('/quiz/')
else:
return redirect('/login/')
else:
return render(request, 'registration/login.html', locals())
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Login</title>
</head>
<body>
{% csrf_token %}
<div class="container">
<h2>Log in</h2>
<form method="post" class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text"
name="username" placeholder="Username">
<input class="form-control mr-sm-2" type="password"
name="password" placeholder="Password">
<button class="btn btn-success" type="submit">送出
</button> 
{% csrf_token %}
</form>
</div>
</body>
</html>
urlpatterns = [
...
path('login', views.login),
]
結果畫面如下: